<template>
  <section class="flex flex-col h-full">
    <el-form
      :model="queryParams"
      @submit.native.prevent
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="所属企业" prop="enterId">
        <el-select
          clearable
          filterable
          v-model="queryParams.enterId"
          placeholder="请选择所属企业"
          class="!w-200px"
        >
          <el-option
            v-for="item in tenantList"
            :key="item.id"
            :label="item.enterName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划编号" prop="planNo">
        <el-input
          v-model="queryParams.planNo"
          :maxlength="50"
          placeholder="请输入计划编号"
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="客户企业" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          :maxlength="50"
          placeholder="请输入客户企业"
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item
        label="所属组织"
        prop="organizationName"
      >
        <el-input
          v-model="queryParams.organizationName"
          :maxlength="50"
          placeholder="请输入所属组织"
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTimes">
        <el-date-picker
          v-model="queryParams.createTimes"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          type="datetimerange"
          class="form-item-height"
        />
      </el-form-item>
      <el-form-item label="生效时间" prop="effectiveTimes">
        <el-date-picker
          v-model="queryParams.effectiveTimes"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          type="datetimerange"
          class="form-item-height"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery"
          >搜索</el-button
        >
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-tabs
      v-model="queryParams.segmentedDeviceCode"
      type="card"
      @tab-change="tabChange"
    >
      <el-tab-pane
        v-for="item in tabs"
        :key="item.value"
        :label="item.label + '（' + item.num + '）'"
        :name="item.value"
      >
      </el-tab-pane>
    </el-tabs>
    <div class="flex justify-between mb-16px">
      <el-button
        v-hasPermi="['salePlan:add']"
        type="primary"
        @click="openForm()"
      >
        新增
      </el-button>
      <div v-if="false">
        <el-button @click="toggle">
          <el-tooltip
            effect="dark"
            content="全屏"
            placement="top-start"
          >
            <div style="width: 22px; height: 22px">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                fill="currentColor"
              >
                <path
                  d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z"
                ></path>
              </svg>
            </div>
          </el-tooltip>
        </el-button>
        <CustomTool
          v-if="false"
          :menuType="'waybillManage'"
          @columnsChange="getCustomColumns()"
        ></CustomTool>
      </div>
    </div>
    <custom-table
      ref="singleTableRef"
      class="flex-1"
      :loading="loading"
      :columns="columns"
      :dataSource="list"
      :height="'100%'"
    >
      <template #index="{ index }">
        {{ index + 1 }}
      </template>
      <template #planNo="{ row }">
        <span
          class="link-text"
          style="color: #409efe"
          @click="openDetailDrawer(row)"
          >{{ row.planNo }}</span
        >
      </template>
      <template #status="{ row }">
        <StatusText
          :type="
            DICT_TYPE.DISPATCH_SALE_TRANSPORT_PLAN_STATUS
          "
          :value="row.status"
          :color="colorStatusMap[row.status]"
        ></StatusText>
      </template>
      <template #operation="{ row }">
        <template v-if="visibleButtons(row).length > 0">
          <el-button
            v-for="(button, index) in visibleButtons(row)"
            :key="index"
            :type="button.type"
            :link="button.link"
            @click="button.action(row)"
            v-hasPermi="button.permissions"
          >
            {{ button.label }}
          </el-button>
        </template>
      </template>
    </custom-table>
    <QrCodeDialog ref="qrCodeDialogRef"></QrCodeDialog>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </section>
  <FormDrawer ref="formDrawerRef" @success="resetQuery" />
  <DetailDrawer ref="detailDrawerRef" />
</template>
<script setup lang="ts" name="SalesPlan">
import * as authorizationManageApi from '@/api/authorizationManage'
import { DICT_TYPE, getJLDictOptions } from '@/utils/dict'
import * as salesPlanApi from '@/api/salesPlan'
import QrCodeDialog from './qrCodeDialog.vue'
import { useFullscreen } from '@vueuse/core'
import { getTenantId } from '@/utils/auth'
import FormDrawer from './formDrawer.vue'
import DetailDrawer from './detailDrawer.vue'
import { cloneDeep } from 'lodash'

const loading = ref(false)
const tenantList = ref([])
const router = useRouter()
const tabs = ref([])
const columns = ref([
  {
    title: '序号',
    field: 'index',
    width: '65px',
    fixed: 'left',
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  },
  {
    title: '所属企业',
    field: 'enterName',
    width: '150px',
    fixed: 'left',
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '计划编号',
    field: 'planNo',
    width: '210px',
    fixed: 'left',
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  },
  {
    title: '状态',
    field: 'status',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  },
  {
    title: '客户企业',
    field: 'customerName',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '产品',
    field: 'productNames',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '交易总量',
    field: '',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '价格',
    field: '',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '装货地址',
    field: '',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '卸货地址',
    field: '',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '开始时间',
    field: 'startTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '结束时间',
    field: 'endTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '创建时间',
    field: 'createTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '所属组织',
    field: 'organizationName',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '操作',
    field: 'operation',
    width: '120px',
    fixed: 'right',
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  }
])
const list = ref([])
const total = ref(0)
const queryFormRef = ref()
const formDrawerRef = ref()
const detailDrawerRef = ref()
const singleTableRef = ref()
const qrCodeDialogRef = ref()
const message = useMessage()
const colorStatusMap = ref({
  1: 'blue',
  2: 'orange',
  3: 'green'
})
const { isFullscreen, toggle } =
  useFullscreen(singleTableRef)
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  enterId: undefined,
  planNo: undefined,
  customerName: undefined,
  organizationName: undefined,
  segmentedDeviceCode: '2',
  createTimes: [],
  effectiveTimes: []
})
const isShowBig = ref(false)

/** 按钮操作 */
const visibleButtons = (row) => {
  const buttons = [
    {
      label: '二维码',
      action: openQrCodeDialog,
      permissions: ['dy:qrcode'],
      type: 'primary',
      link: true,
      visible: true
    },
    {
      label: '删除',
      action: deleteDispatch,
      permissions: ['salesPlan:delete'],
      type: 'primary',
      link: true,
      visible: true
    }
  ]
  return buttons.filter((btn) => btn.visible).slice(0, 3)
}

const getOutTenantList = async () => {
  const res =
    await authorizationManageApi.getOutTenantListByIdentity(
      { identity: 1 }
    )
  tenantList.value = res || []
}

const getTabList = async () => {
  const list = getJLDictOptions(
    DICT_TYPE.DISPATCH_SALE_TRANSPORT_PLAN_STATUS
  )
  const res = await salesPlanApi.getSegmentedDevice({
    ...queryParams.value,
    dispatchTenantId: getTenantId()
  })
  tabs.value = handleObj(list, res)
}

const handleObj = (list, obj) => {
  const result = list.map((e) => {
    e.num = obj[e.label] || 0
    return e
  })
  return result
}

const getList = async () => {
  loading.value = true
  try {
    const res = await salesPlanApi.getSalePlanPage({
      ...queryParams.value,
      dispatchTenantId: getTenantId()
    })
    if (res.code === 0) {
      total.value = res.data?.total || 0
      list.value = res.data?.list || []
    } else if (res.code === 100910003) {
      loading.value = false
      await message.confirm(res.msg)
      refreshAuthorize()
    } else if (res.code === 100910004) {
      loading.value = false
      await message.confirm(res.msg)
      router.push({
        path: '/authManageCatalog/authorizationManage'
      })
    } else {
      message.error(res.msg)
    }
  } finally {
    loading.value = false
  }
}

const refreshAuthorize = async () => {
  await salesPlanApi.refreshAuthorize()
  queryParams.value.segmentedDeviceCode = '0'
  getOutTenantList()
  getTabList()
  getList()
}

const openQrCodeDialog = async (row) => {
  const data = await salesPlanApi.getSalePlanDetail({
    id: row.id
  })
  qrCodeDialogRef.value.open(data)
}

const deleteDispatch = async (row) => {
  await message.confirm('确定要删除吗?')
  await salesPlanApi.deletePlan(
    row.id,
    row.enterId,
    row.customerId
  )
  message.success('删除成功')
  resetQuery()
}

const openDetailDrawer = async (row) => {
  await getBiddingInfo(row)
  if (isShowBig.value) {
    detailDrawerRef.value.open(row)
  } else {
    message.warning('暂无计划详情')
  }
}

const getBiddingInfo = async (row) => {
  const res = await salesPlanApi.getBiddingInfo({
    outTenantId: row.enterId
  })
  isShowBig.value = res.isBidding
}

const getCustomColumns = () => {
  console.log('自定义列')
}

const openForm = () => {
  formDrawerRef.value.open()
}

const tabChange = (tab) => {
  queryParams.value.segmentedDeviceCode = tab
  queryParams.value.pageNo = 1
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getTabList()
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 初始化 **/
onMounted(async () => {
  await getOutTenantList()
  getTabList()
  getList()
})
</script>
<style lang="scss" scoped>
:deep(.el-table__header-wrapper .el-checkbox__inner) {
  display: none !important;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-table {
  :deep(.el-button) {
    height: 30px !important;
    line-height: 30px !important;
  }
}

.link-text {
  color: #409efe;
  cursor: pointer;
}

:deep(.el-form-item--default) {
  margin-bottom: 16px;
}

:deep(.el-table .cell) {
  line-height: 30px;
}
</style>
